package com.jgp.sys.repository;

import com.jgp.common.persistence.Model;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * 项目   sys
 * 作者   loufei
 * 时间   2018/2/25
 */
public class JGPRepositoryFactoryBean<R extends JpaRepository<T, I>, T extends Model,
        I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    public JGPRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {
        return new JGPBaseRepositoryFactory(em);
    }

    //创建一个内部类，该类不用在外部访问
    private static class JGPBaseRepositoryFactory
            extends JpaRepositoryFactory {

        private final EntityManager em;

        public JGPBaseRepositoryFactory(EntityManager em) {
            super(em);
            this.em = em;
        }
        //设置具体的实现类是
        @Override
        protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information, EntityManager entityManager) {
            return new JGPRepositoryImpl(getEntityInformation(information.getDomainType()), em);
        }

        //设置具体的实现类的class
        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return JGPRepositoryImpl.class;
        }
    }

}
